AddCSLuaFile( "cl_init.lua" );
AddCSLuaFile( "shared.lua" );

include( "shared.lua" );

ENT.Spawnable = true;

function ENT:SpawnFunction( ply, tr )

	if( !tr.Hit ) then return end
	
	local pos = tr.HitPos + tr.HitNormal * 24;
	
	local ent = ents.Create( self.ClassName );
	ent:SetPos( pos );
	ent:Spawn();
	ent:Activate();
	
	return ent;
	
end

function ENT:Initialize()
	
	self:SetModel( "models/props_lab/hevplate.mdl" );
	self:PhysicsInit( SOLID_VPHYSICS );
	self:SetMoveType( MOVETYPE_VPHYSICS );
	self:SetSolid( SOLID_VPHYSICS );
	
	local phys = self:GetPhysicsObject();
	if( phys and phys:IsValid() ) then
		
		phys:Wake();
		
	end
	
	self:SetUseType( SIMPLE_USE );
	
	C.ClearLinks( self );
	
end

function ENT:Use( act, call, type, val )
	
	if( self:AccessResource( RES_OXYGEN, 1000 ) and
		self:AccessResource( RES_COOLANT, 1000 ) and
		self:AccessResource( RES_ENERGY, 1000 ) ) then
		
		local o = self:GetContainer( RES_OXYGEN, 1000 );
		if( o and o:IsValid() ) then
			
			o:RemoveResource( RES_OXYGEN, 1000 );
			
		end
		
		local c = self:GetContainer( RES_COOLANT, 1000 );
		if( c and c:IsValid() ) then
			
			c:RemoveResource( RES_COOLANT, 1000 );
			
		end
		
		local e = self:GetContainer( RES_ENERGY, 1000 );
		if( e and e:IsValid() ) then
			
			e:RemoveResource( RES_ENERGY, 1000 );
			
		end
		
		act:SetNWFloat( "C_S", CurTime() + 300 );
		
		self:EmitSound( Sound( "weapons/physgun_off.wav" ) );
		
	end
	
end

function ENT:CheckLinks()
	
	for k, v in pairs( self.Links ) do
		
		if( !v or !v:IsValid() ) then
			
			table.remove( self.Links, k );
			continue;
			
		end
		
		if( v:GetPos():Distance( self:GetPos() ) > 1024 ) then
			
			table.remove( self.Links, k );
			
			self:EmitSound( Sound( "weapons/stunstick/spark" .. tostring( math.random( 1, 3 ) ) .. ".wav" ) );
			
		end
		
	end
	
end

function ENT:AccessResource( res, amt )
	
	for _, v in pairs( self.Links ) do
		
		if( v.CosmicType == CE_CONTAINER and v:GetAmount( res ) >= amt ) then
			
			return true;
			
		end
		
	end
	
	return false;
	
end

function ENT:GetContainer( res, amt )
	
	for _, v in pairs( self.Links ) do
		
		if( v.CosmicType == CE_CONTAINER and v:GetAmount( res ) >= amt ) then
			
			return v;
			
		end
		
	end
	
end

function ENT:Think()
	
	self:CheckLinks();
	
end